package com.example.order.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author : zhayh
 * @date : 2021-5-8 16:35
 * @description :
 */

@Configuration
public class OrderQueueConfig {
    // 创建直连交换机
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange("exchange.order");
    }

    // 1. 队列1：待确认订单队列
    @Bean
    public Queue orderConfirmQueue() {
        return new Queue("queue.order.confirm");
    }

    // 2. 队列2：待配送订单队列，该队列的消息超过1分钟未被骑手处理，就自动转为商家配送订单
    @Bean
    public Queue orderDeliverQueue() {
        HashMap<String, Object> params = new HashMap<>();
        // 设置消息到期后用于转发的交换机
        params.put("x-dead-letter-exchange", "exchange.order");
        // 设置消息到期后消息转发的去向，转到队列3
        params.put("x-dead-letter-routing-key", "shopDeliver");
        // 设置此队列消息的有效时长为1分钟
        params.put("x-message-ttl", 60 * 1000);
        return new Queue("queue.order.deliver", true, false, false, params);
    }

    //. 3. 队列3： 无人配送的订单队列
    @Bean
    public Queue shopDeliverQueue() {
        return new Queue("queue.shop.deliver");
    }

    // 4. 队列4： 配送完成的订单队列
    @Bean
    public Queue orderCompleteQueue() {
        return new Queue("queue.order.complete");
    }

    @Bean
    public Binding bindingOrderConfirmToOrderExchange() {
        return BindingBuilder.bind(orderConfirmQueue())
                .to(orderExchange())
                .with("confirm");
    }

    @Bean
    public Binding bindingOrderDeliverToOrderExchange() {
        return BindingBuilder.bind(orderDeliverQueue())
                .to(orderExchange())
                .with("deliver");
    }

    @Bean
    public Binding bindingShopDeliverToOrderExchange() {
        return BindingBuilder.bind(shopDeliverQueue())
                .to(orderExchange())
                .with("shopDeliver");
    }

    @Bean
    public Binding bindingOrderCompleteToOrderExchange() {
        return BindingBuilder.bind(orderCompleteQueue())
                .to(orderExchange())
                .with("complete");
    }
}
